package org.seeplnframework.skyeye.common.alarmmerge;

import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ly
 * @date 2023/1/18
 * <pre>
 *     持有每个接口log.error抛出来的带有数量上限的exception
 *     外层key：接口uri
 *     内层key：uri+hash(message)
 *     内层value：message
 * </pre>
 */
@UtilityClass
public class AlarmInterfaceUriInfoHolder {

    private final static ConcurrentHashMap<String, AlarmInterfaceUriExceptionLRU<String, String>> holder = new ConcurrentHashMap<>(100);

    public void put(String uri, String hash, String message) {
        if (holder.contains(uri)) {
            holder.get(uri).putIfAbsent(hash, message);
            return;
        }
        holder.putIfAbsent(uri, new AlarmInterfaceUriExceptionLRU<>(50, ImmutableMap.of(hash, message)));
    }

    public void remove(String hashed) {
        String uri = Optional
                .ofNullable(hashed)
                .filter(StringUtils::isNotBlank)
                .map(it -> Splitter.on("#").splitToList(it))
                .orElseGet(() -> ImmutableList.of("unknown"))
                .get(0);

        Optional.ofNullable(holder.get(uri))
                .ifPresent(it -> it.remove(hashed));
    }

    public AlarmInterfaceUriExceptionLRU<String, String> allKnownExceptions(String uri) {
        return holder.get(uri);
    }
}
